package cn.wangliang181230.boot.web.propertysource;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * 操作系统工具类
 *
 * @author 王良 / 841369634@qq.com
 * @since 2019/6/18 13:18
 */
public final class NetUtil {

	private NetUtil() {
		throw new RuntimeException("此工具类不允许实例化");
	}

	public static final String ERROR_IP = "0.0.0.0";

	/**
	 * 获取当前主机的 IP地址（多个网卡时，自动取第一个）
	 * 注：该方法有时候会获取到127.0.0.1，不建议使用，建议使用getInnerIp();
	 */
	public static String getIp() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostAddress();
		} catch (Exception e) {
			return ERROR_IP;
		}
	}

	// 所有网卡IP缓存
	private static List<String> ipListCache = null;
	private static Date ipListCacheTime = null;

	/**
	 * 获取所有网卡的IP
	 */
	public static List<String> getIpList(boolean cacheEnable) {
		// 10分钟缓存
		if (cacheEnable && ipListCacheTime != null && System.currentTimeMillis() - ipListCacheTime.getTime() < 10 * 60 * 1000) {
			return ipListCache;
		}

		List<String> result = new ArrayList<>();
		Enumeration<NetworkInterface> netInterfaces;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> addresses = ni.getInetAddresses();
				while (addresses.hasMoreElements()) {
					ip = addresses.nextElement();
					if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1 && !"127.0.0.1".equals(ip.getHostAddress())) {
						result.add(ip.getHostAddress());
					}
				}
			}
		} catch (Exception e) {
			// do nothing
		}

		if (result.isEmpty()) {
			String ip = getIp();
			if (!result.contains(ip)) result.add(ip);
		}

		ipListCache = result;
		ipListCacheTime = new Date();

		return result;
	}

	public static List<String> getIpList() {
		return getIpList(true);
	}

}
